package org.lys.poi;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.apache.commons.io.output.ByteArrayOutputStream;
import org.apache.poi.hwpf.HWPFDocument;
import org.apache.poi.hwpf.converter.WordToHtmlConverter;
import org.w3c.dom.Document;

public class WordExcelToHtml {

	public static final String inputFile = "I://template.doc";

	public static void main(String argv[]) {
		try {
			HWPFDocument wordDocument = new HWPFDocument(new FileInputStream(
					inputFile));
			WordToHtmlConverter wordToHtmlConverter = new WordToHtmlConverter(
					DocumentBuilderFactory.newInstance().newDocumentBuilder()
							.newDocument());

			wordToHtmlConverter.processDocument(wordDocument);
			Document htmlDocument = wordToHtmlConverter.getDocument();

			ByteArrayOutputStream out = new ByteArrayOutputStream();
			DOMSource domSource = new DOMSource(htmlDocument);
			StreamResult streamResult = new StreamResult(out);

			TransformerFactory tf = TransformerFactory.newInstance();
			Transformer serializer = tf.newTransformer();
			serializer.setOutputProperty(OutputKeys.ENCODING, "utf-8");
			serializer.setOutputProperty(OutputKeys.METHOD, "html");
			serializer.setOutputProperty(OutputKeys.INDENT, "yes");
			serializer.transform(domSource, streamResult);
			out.close();
			String template = new String(out.toByteArray());
			template = styleToHtml(template);
			template = createDialogPanel(template);
			writeFile(template);
			// getWordAndStyle(inputFile);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 写文件
	 * 
	 * @param s
	 */
	public static void writeFile(String s) {
		FileOutputStream fos = null;
		BufferedWriter bw = null;
		try {
			File file = new File("g://a.html");
			fos = new FileOutputStream(file);
			bw = new BufferedWriter(new OutputStreamWriter(fos));
			bw.write(s);
		} catch (FileNotFoundException fnfe) {
			fnfe.printStackTrace();
		} catch (IOException ioe) {
			ioe.printStackTrace();
		} finally {
			try {
				if (bw != null)
					bw.close();
				if (fos != null)
					fos.close();
			} catch (IOException ie) {
			}
		}
	}

	/**
	 * @Description: 將css写入html中
	 * @Create: 2012-11-4 下午5:50:37
	 * @author lys
	 * @update logs
	 * @param template
	 * @throws Exception
	 */
	public static String styleToHtml(String template) {
		Pattern pattern = Pattern.compile("\\.(\\w+)\\{(.*)\\}");
		Matcher matcher = pattern.matcher(template);
		while (matcher.find()) {
			String className = matcher.group(1);
			String classStyle = matcher.group(2);
			template = template.replace("class=\"" + className + "\"",
					"style=\"" + classStyle + "\"");
		}
		return template;
	}

	/**
	 * @Description: 生成对话框panel中的html
	 * @Create: 2012-11-4 下午6:30:47
	 * @author lys
	 * @update logs
	 * @param template
	 * @return
	 * @throws Exception
	 */
	public static String createDialogPanel(String template) {
		Pattern pattern = Pattern.compile("<body .*>");
		Matcher matcher = pattern.matcher(template);
		int index = 0;
		while (matcher.find()) {
			String body = matcher.group();
			index = template.indexOf(body);
			template = template.substring(index + body.length());
		}
		index = template.indexOf("</body>");
		template = template.substring(0, index).trim();
		// 根据用户指定插入input

		template += "<input type=\"hidden\" name=\"sqbmbId\" value=${sqbmbId}>";
		template += "<input type=\"hidden\" name=\"sqbId\" value=${sqbId}>";
		// 只读字段
		pattern = Pattern.compile("[rR]\\.(\\w+)");
		StringBuffer sb = new StringBuffer();
		matcher = pattern.matcher(template);
		while (matcher.find()) {
			String fieldName = matcher.group(1);
			// 注意$前要加\\
			String replaceStr = "<input type=\"text\" name=\"r_" + fieldName+ "\" value=\"\\${" + fieldName + "}\" style=\"width:100%; border:0px\" readonly = \"readonly\"/>";
			matcher.appendReplacement(sb, replaceStr);
		}
		matcher.appendTail(sb);//将没匹配的添加到sb中
		template = sb.toString();
		//填写字段
		pattern = Pattern.compile("[wW]\\.(\\w+)");
		sb = new StringBuffer();
		matcher = pattern.matcher(template);
		while (matcher.find()) {
			String fieldName = matcher.group(1);
			// 注意$前要加\\
			String replaceStr = "<input type=\"text\" name=\"w_" + fieldName+ "\" value=\"\\${" + fieldName + "}\" style=\"width:100%; border:0px\"/>"
					+"<input type=\"hidden\" name=\""+fieldName+"_sqbmxId\"  value=\"\\${"+fieldName+"_sqbmxId}\"/>";
			matcher.appendReplacement(sb, replaceStr);
		}
		matcher.appendTail(sb);//将没匹配的添加到sb中
		return sb.toString();
	}
}
